<template>
  <div>
    <el-form :inline="true" :model="queryForm" class="demo-form-inline">
      <el-form-item label="兑换订单管理">
        <el-input v-model="queryForm.kw" placeholder="订单号" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="list">
      <!-- <el-table-column label="序号" type="index" width="100" /> -->
      <el-table-column align="center" label="" width="100">
        <template #default="scope">
          <el-avatar shape="square" size="medium" :src="scope.row.product.mainPic"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="兑换时间/订单号" align="center" prop="updatedAt">
        <template #default="scope">
            <div>{{timestampToDayHM(scope.row.orderTime)}}</div>
            <div>{{scope.row.orderCode}}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="user.nickName" label="会员">
      </el-table-column>
      <el-table-column align="center" prop="title" label="兑换商品">
        <template #default="scope">
          <strong>{{ scope.row.product.name }}</strong>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="totalPrice" label="消耗积分">
      </el-table-column>
      <el-table-column label="状态" align="center" prop="tags">
        <template #default="scope">
          <el-tag type="danger" v-if="scope.row.status==1">待发货</el-tag>
          <el-tag type="success" v-if="scope.row.status==2">已发货</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="title" label="收货信息" width="200">
        <template #default="scope">
          <div>{{scope.row.fullAddress}}</div>
          <div>{{scope.row.receiveName}} {{scope.row.mobile}}</div>
        </template>
      </el-table-column>
      
      <!-- <el-table-column align="center" sortable prop="floor" label="最后更新">
        <template slot-scope="scope">
          <div>{{scope.row.lastUpdate|timestampToTime}}</div>
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button link type="primary" v-if="scope.row.status==1" icon="Check" @click="onVerify(scope.row.orderId, 1)">发货</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination background layout="prev, pager, next" v-model:page-size="queryForm.pageSize" v-model:current-page="queryForm.pageNo" :total="total" @current-change="getList" /> 

    <!--详情对话框-->
    <el-dialog v-model="openDetail" :title="title" width="60%" append-to-body v-if="detailData">
      <!-- <el-descriptions class="margin-top" :column="2" border>
          <el-descriptions-item label="课程名称" labelStyle="width: 160px;">{{ detailData.ruleName }}</el-descriptions-item>
          <el-descriptions-item label="模板编号" labelStyle="width: 160px;">{{ detailData.ruleCode }}</el-descriptions-item>
          <el-descriptions-item label="版本号" labelStyle="width: 160px;">{{ detailData.version }}</el-descriptions-item>
          <el-descriptions-item label="创建时间" labelStyle="width: 160px;">{{ timestampToDayHM(detailData.createTime) }}</el-descriptions-item>
      </el-descriptions> -->
      <div class="introduction">{{ detailData.content }}</div>
      <div class="detail-pics">
        <ul class="img-list">
          <li v-for="(pic,i) in detailData.picList" :key="i" class="img-li" onclick="(function(e){e.stopPropagation()}(event))">
            <a :href="pic" target="_blank">
              <img :src="pic" class="avatar aspect-fill" style="width: 250px;height: 180px;"/>
            </a>
          </li>
        </ul>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, nextTick, toRef } from "vue";
import baseService from "@/service/baseService";
import { ElMessage, ElMessageBox } from "element-plus";
import { timestampToDayHM, timestampToHM, timestampToDate, formatAmount } from "@/utils/utils"
import { regionData, codeToText, TextToCode } from 'element-china-area-data'
import { fileUploader } from '@/utils/upload.js'
import { useRouter, useRoute } from 'vue-router';

import { EluiChinaAreaDht } from 'elui-china-area-dht'
const chinaData = new EluiChinaAreaDht.ChinaArea().chinaAreaflat

const router = useRouter();
const route = useRoute();
// 查询参数
const queryForm = reactive({
  kw: '',
  pageNo: 1,
  pageSize: 10
});
// 列表内容数量
const total = ref(0);
// 列表是否加载
const loading = ref(true);
// 列表返回值
const list = ref<any[]>([]);
const selectedCityOptions = ref<any[]>([]);

// 表单实例
const formRef = ref();
// 是否打开弹出框
const open = ref(false);
const isEdit = ref(0);
const openDetail = ref(false);
// 弹出框标题
const title = ref('');
const detailData = ref();
// 提交表单数据
let editForm = toRef(
  reactive({
    id: '',
    title: '',
    pics: '',
    mainPic: '',
    tags: '',
    content: '',
    likes: 0,
    favs: 0,
    activityDate: '',
    status: 1
  })
);
const options = ref(regionData)
const selectedOptions = ref<any>([])
//多图上传的返回图片url数组
const pics = ref<any>([])
const uploadUrlPath = ref();

// 表单验证
const rules = ref({
  title: [{ required: true, message: "请输入", trigger: "blur" }],
  tags: [{ required: true, message: "请输入", trigger: "blur" }],
  activityDate: [{ required: true, message: "请输入", trigger: "blur" }],
  content: [{ required: true, message: "请输入", trigger: "blur" }],
});

/**
 * 查询列表
 */
const getList = () => {
  loading.value = true;
  baseService
    .post("/admin/order/list", queryForm).then((res) => {
      loading.value = false;
      if (res.code === 200) {
        list.value = res.data.records;
        total.value = res.data.totalrecord;
      } else {
        list.value = [];
      }
    })
    .catch(() => {
      loading.value = false;
    });
};

/**
 * 搜索按钮操作
 */
function handleQuery() {
  queryForm.pageNo = 1;
  getList();
}

/**
 * 表单重置
 */
function reset() {
  editForm.value = {
    id: '',
    title: '',
    pics: '',
    mainPic: '',
    tags: '',
    content: '',
    activityDate: '',
    likes: 0,
    favs: 0,
    status: 1
  };
  pics.value = []

  nextTick(() => {
    formRef.value?.resetFields();
  });
}

/**
 * 新增按钮操作
 */
function handleAdd() {
  reset();
  open.value = true;
  isEdit.value = 0;
  console.log('图片:',pics.value)
  title.value = "添加";
}

//显示详情
function showDetail(data: any){
    openDetail.value = true;
    title.value = "活动正文";
    detailData.value = data
  }

/**
 * 修改按钮操作
 * @param id 主键
 */
function handleUpdate(id: string) {
  open.value = true;
  title.value = "修改";
  isEdit.value = 1;
  reset();
  baseService.get(`/admin/activity/info/${id}`).then((res) => {
    if (res.code === 200) {
      editForm.value = res.data;
      pics.value = res.data.pics.split(',')
    }
  });
}

function onVerify(id: string, status: number) {
  let msg = '确认要要发货吗?'
  ElMessageBox.confirm(msg, "提示").then(() => {
    baseService.get(`/admin/order/send/${id}`).then((res) => {
      if (res.code === 200) {
        ElMessage.success('已发货');
        getList()
      }else{
        ElMessage.error('发货失败');
      }
    });
  })
}


/**
 * 提交按钮
 */
function submitForm() {
  formRef.value.validate((valid: boolean) => {
    if (!valid) return;
    console.log('图片字段', pics.value)
    editForm.value.pics = pics.value.join(',')
    baseService.post(`/admin/activity/save`, editForm.value).then((res) => {
      if (res.code === 200) {
        ElMessage.success('发布成功，请耐心等候管理员审核');
        open.value = false;
        getList();
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
}

/**
 * 删除按钮操作
 * @param id 主键
 */
function handleDelete(id: any, optType: number) {
  let msg = '确认要删除该内容吗?'
  ElMessageBox.confirm(msg, "提示").then(() => {
    baseService.get(`/admin/activity/delete/${id}`).then((res) => {
      if (res.code === 200) {
        ElMessage.success(res.msg);
        getList();
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
}


function handlePreview(file: any) {
    console.log(file);
}
function handleRemove(file: any, fileList: any) {
  alert('移除')
    //return this.$confirm(`确定移除 ${file.name}？`);
}
function beforeRemove(file: any, fileList: any) {
  alert('移除')
    // return this.$confirm(`确定移除 ${file.name}？`);
}

  // 图片上传
function uploadSectionFile(file: any) {
  console.log('选定图片！',file)
  const typeArr = ["image/png", "image/gif", "image/jpeg", "image/jpg"];
  const isJPG = typeArr.indexOf(file.raw.type) !== -1;
  const isLt3M = file.size / 1024 / 1024 < 3;
  if (!isJPG) {
    // ElMessage.error("只能是图片!");
    // this.$refs.upload.clearFiles();
    // this.files = null;
    return;
  }
  if (!isLt3M) {
    // ElMessage.error("上传图片大小不能超过 3MB!");
    // this.$refs.upload.clearFiles();
    // this.files = null;
    return;
  }
  // FormData 对象
  var formData = new FormData();
  // 文件对象
  formData.append("myFile", file.raw)
  console.log('上传图片表单：', formData)
  fileUploader(formData).then((res) => {
    if (res.data.errno==0) {
      //this.photoObj = res.data.data.objectId;
      console.log('图片上传成功！', res.data)
      pics.value.push(res.data.data);
    } else {
      // ElMessage.error(res.data.message);
    }
  })
}
  // 上传LOGO图片
function uploadLogoFile(file: any){
  const typeArr = ["image/png", "image/gif", "image/jpeg", "image/jpg"];
  const isJPG = typeArr.indexOf(file.raw.type) !== -1;
  const isLt3M = file.size / 1024 / 1024 < 3;
  if (!isJPG) {
    // ElMessage.error("只能是图片!");
    // this.$refs.upload.clearFiles();
    // this.files = null;
    return;
  }
  if (!isLt3M) {
    // ElMessage.error("上传图片大小不能超过 3MB!");
    // this.$refs.upload.clearFiles();
    // this.files = null;
    return;
  }
  var formData = new FormData();
  formData.append("myFile", file.raw)
  fileUploader(formData).then((res) => {
    console.log('LOGO上传成功', res)
    if (res.data.errno==0) {
      editForm.value.mainPic=res.data.data[0]
    } else {
      // ElMessage.error(res.data.message);
    }
  })
}
// 移除LOGO图片
function handleRemoveLogo(file: any){
  editForm.value.mainPic=''
  console.log('移除LOGO图片！',editForm.value.mainPic)
}

// 移除多图中的其中一张
function handleRemovePics(idx: number){
  console.log('移除图片下标为：', idx)
  pics.value.splice(idx, 1);
}

// 上传(文件)图片失败
function uploadEditorError(res: any, file: any) {
  console.log(res);
  console.log(file);
  //页面提示
  ElMessage.error('上传图片失败')
  //取消上传动画
  // this.quillUpdateImg = false;
}
//上传图片之前async
function beforeEditorUpload(res: any, file: any){
  //显示上传动画
  // this.quillUpdateImg = true;
  console.log(res);
}
//上传组件返回的结果
function uploadResult (res: any){
  uploadUrlPath.value=res;
}

getList();
</script>

<style scoped>
.price{
color: #F56C6C;
font-weight: bold;
}
.pointer{
  cursor: pointer;
}
.pointer:HOVER{
  color: #409eff;
}
.introduction{
width: 80%;
margin: 15px auto;
white-space: pre-line;
}
.addpic{
font-size: 22px;
padding: 20px 25px 15px 25px;
border: 2px dashed #ccc;
color: #888;
height: 68px;
}
.img-list{
display: flex;
flex-wrap: wrap;
}
.img-list .img-li{
width: 260px;
position: relative;
margin-right: 10px;
}
.logo-remove{
font-size: 22px;
position: absolute;
top: 10px;
right: 10px;
color: #f00;
cursor: pointer;
text-shadow: #000 4px 4px 5px;
}
.logo-remove .el-icon{
box-shadow: #fff 3px 5px 6px;
background-color: #fff;
}
.logo-remove:HOVER{
color: #F56C6C;
}
.detail-pics{
  width: 80%;
  margin-top: 30px;
}
</style>
